from  flask import Flask,render_template
from flask_sqlalchemy import SQLAlchemy
import update_price as up

app=Flask(__name__)

db=SQLAlchemy(app)



class Config(object):
    """配置参数"""
    #sqlalchemy的配置参数
    SQLALCHEMY_DATABASE_URI="mysql://root:123456@127.0.0.1:3306/test"
    #设置sqlalchemy自动跟踪数据库
    SQLALCHEMY_TRACK_MODIFICATIONS = True
    SQLALCHEMY_COMMIT_TEARDOWN = True

app.config.from_object(Config)


class Price(db.Model):
    __tablename__ = 'sql_prices'
    # id = Column(String(20), primary_key=True)
    # name = Column(String(20))
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    # name = Column(String(200))
    # money = Column(Float)
    datetime = db.Column(db.DATE, unique=True)
    price = db.Column(db.Float)

    def __init__(self, datetime, price):
        self.datetime = datetime
        self.price = price

    # def __repr__(self):
        # return "price is %f" %self.price

# for price in  Price.query.all():
    # print(price.datetime)

db.create_all()
@app.route("/add/")
def add():
    date,price = up.price_main()
    results = Price.query.filter(Price.datetime == date).first()
    if results:
        return "数据已存在,不用添加"
    else:
        date_price = Price(date,price)
        db.session.add(date_price)
        db.session.commit()
        return "添加成功"

@app.route("/")
def hello():
    return "HELLO"

@app.route("/select/")
def select():
    result = Price.query.all()
    # print (result.price)
    return render_template("select.html", result=result)

@app.route("/edit/")
def edit():
    result = Price.query.filter(Price.id == 1).first()
    result.price = 100000
    db.session.commit()
    return "修改成功"

@app.route("/delete/")
def delete():
    results = Price.query.filter(Price.datetime == None).all()
    for result in results:
        db.session.delete(result)
    db.session.commit()
    return "删除完成"

if __name__ == '__main__':
    app.run(debug=True)